package com.rlyy.basic.support;

import com.rlyy.common.param.Request;
import com.rlyy.common.response.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 拦截执行链
 *
 * @author yuanqinglong
 * @since 2021/9/13 10:48
 */
@Component
public class InterceptionExecuteChain {


    @Autowired(required = false)
    private List<IRequestInterceptionProcessor> requestInterceptionProcessors;


    /**
     * 在执行之前
     *
     * @param grpcRequest 完整的请求
     */
    public void beforeExecute(Request grpcRequest) throws Exception {
        if (!CollectionUtils.isEmpty(requestInterceptionProcessors)) {
            for (IRequestInterceptionProcessor requestInterceptionProcessor : requestInterceptionProcessors) {
                requestInterceptionProcessor.beforeHandler(grpcRequest);
            }
        }
    }


    /**
     * 业务执行后执行
     *
     * @param grpcRequest 完整的请求
     * @param result      结果
     */
    public void afterExecute(Request grpcRequest, Result result) throws Exception {
        if (!CollectionUtils.isEmpty(requestInterceptionProcessors)) {
            for (int i = requestInterceptionProcessors.size() - 1; i >= 0; i--) {
                requestInterceptionProcessors.get(i).postHandler(grpcRequest, result);
            }
        }
    }


}
